package jjn.carl.stack_queue;

import java.util.Set;
import java.util.Stack;

/**
 * @author Jiang Jining
 * @since 2023-07-09 15:16
 */
public class LeetCode150 {
    public int evalRPN(String[] tokens) {
        Set<String> operations = Set.of("+", "-", "*", "/");
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (isOperation(token, operations)) {
                int first = stack.pop();
                int second = stack.pop();
                stack.push(calc(first, second, token));
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }
    
    private boolean isOperation(String token, Set<String> operations) {
        return operations.contains(token);
    }
    
    private int calc(int first, int second, String operation) {
        if ("+".equals(operation)) {
            return second + first;
        }
        if ("-".equals(operation)) {
            return second - first;
        }
        if ("*".equals(operation)) {
            return second * first;
        }
        return second / first;
    }
    
    public static void main(String[] args) {
        int result = new LeetCode150().evalRPN(new String[]{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"});
        System.out.println("result = " + result);
    }
}
